// 获取数据库
const db = wx.cloud.database()
// 获取集合
const goods_col = db.collection('goods')
const carts_col = db.collection('carts')

import {ml_showloading,
  ml_hideloading,
  ml_showtoast,
  ml_showtoastSuccess} from '../../utils/asyncWX'

Page({
  data: {
    _page:0,
    goods:[],
    swiper:[],
    hasMore:true,
  },

  onLoad: function (options) {
    this.loadListData()
    this.loadSwiperData()
  },

  onPullDownRefresh() {
//app.json中设置enablePulldownRefresh:true
//重置数据
    this.setData({
      goods :[],
      _page :0,
      hasMore : true
    })
    this.loadListData()
  },
  async addCart(e) {
    //获得当前对象
    let {item} = e.currentTarget.dataset
    //取出对应数据，更新数量
    try{
      let res = await carts_col.doc(item._id).get()
      console.log('有值')
      await carts_col.doc(item._id).update({
        data:{
          num: db.command.inc(1)
        }
      })
    }catch{
//没有数据就增加一条数据
       await carts_col.add({
        data : {
          _id :item._id,
          imageSrc : item.imageSrc,
          price :item.price,
          title :item.title,
          num : 1,
          selected : true
        }
      })
    }
  },
  async onReachBottom() {
    //console.log(this.data.hasMore)
    if(!this.data.hasMore) {
      await ml_showtoast('没有更多数据了')
    }else{
      this.loadListData()
    }
  },
  //获取轮播图数据
  async loadSwiperData() {
    let res = await goods_col.limit(3).orderBy('count','desc').get()
   // console.log('轮播数据',res.data)
    this.setData({
      swiper:res.data
    })
  },
//获取列表数据
  async loadListData() {
    const LIMIT =5
    let _page = this.data._page
    let goods = this.data.goods
    await ml_showloading()
    let res = await goods_col.limit(LIMIT).skip(_page*LIMIT).get()
    //let res = await goods_col.get()

    await ml_hideloading()
    //console.log('列表数据', res.data)
    wx.stopPullDownRefresh()
    this.setData({
      goods:goods.concat(res.data),
      _page:++_page,
      hasMore:res.data.length === LIMIT
    })
  }
})